const express = require('express');
const router = express.Router();
const {Setting} = require('../../models');
const {Op} = require('sequelize');
const {NotFoundError, success, failure} = require('../../Utils/response');


// 根据id查询单个系统设置
router.get('/', async function (req, res,) {
    try {
        const setting = await getSetting();
        success(res, '查询系统设置成功。', {setting})
    } catch (error) {
        failure(res, error);
    }
});


// 根据id--更新单个系统设置
router.put('/', async function (req, res,) {
    try {
        const setting = await getSetting();
        const body = filterBody(req.body)
        await setting.update(body)
        success(res, '更新系统设置成功。', {setting},)
    } catch (error) {
        failure(res, error);
    }
});

// 公共方法：查询当前系统设置
async function getSetting() {
    // 查询系统设置
    const setting = await Setting.findOne();
    if (!setting) {
        throw new NotFoundError(`初始的系统设置没有找到`)
    }
    return setting
}

// 公共方法：白名单过滤  ===永远不要相信用户所填写的数据
function filterBody(req) {
    return {
        name: req.name,
        icp: req.icp,
        copyright: req.copyright,
    }

}

module.exports = router;
